import gtk
import gtk.glade
from Variable import Variable

class AddVariableWin:
    def __init__( self, variablesInUse, gladefile, cmakeVars, configWin):
        self.__varInUse = variablesInUse
        self.__gladefile = gladefile
        self.__cmakeVars = cmakeVars
        self.__configWin = configWin
        self.__var = Variable()
        self.__varname = self.__type = self.__value = ''
        self.__xml = gtk.glade.XML( self.__gladefile)
        if self.__xml:
            self.__win = self.__xml.get_widget( "AddVariableWindow")
            #self.__win.hide()
            self.__win.connect( "destroy", self.__onCancel)
            self.__handlers = { "on_btnOk_clicked": self.__onOk
                              , "on_btnCancel_clicked": self.__onCancel 
                              , "on_comboVarName_changed": self.__onVarChanged
                              , "on_cmbboxVarType_changed": self.__onTypeChanged
                              , "on_entryVarValue_changed": self.__onValueChanged}
            self.__xml.signal_autoconnect( self.__handlers)
            self.__comboName = self.__xml.get_widget( "comboVarName")
            self.__liststore = gtk.ListStore( str)
            self.__comboName.set_model( self.__liststore)
            self.__fillComboVars()
            self.__comboType = self.__xml.get_widget( "cmbboxVarType")
            self.__comboType.child.set_property( 'editable', False)
            self.__entryValue = self.__xml.get_widget( "entryVarValue")
            self.__btnOk = self.__xml.get_widget( "btnOk")
            self.__btnOk.set_sensitive( False)

    def show( self):
        self.__win.show_all()

    def __fillComboVars( self):
        varlist = self.__cmakeVars.keys()
        varlist.sort()
        for varname in varlist:
            self.__liststore.append( [varname])
        self.__comboName.set_text_column( 0)

    def __try2EnableOk( self):
        if len( self.__varname) and len( self.__type) and len( self.__value):
            self.__btnOk.set_sensitive( True)
        else:
            self.__btnOk.set_sensitive( False)
            
    def __onVarChanged( self, combo):
        self.__varname = combo.child.get_text()
        if self.__varname in self.__cmakeVars.keys():
            self.__comboType.child.set_text( self.__cmakeVars[ self.__varname])
        self.__try2EnableOk()

    def __onTypeChanged( self, combo):
        model = self.__comboType.get_model()
        index = self.__comboType.get_active()
        self.__type = model[ index][ 0]
        self.__try2EnableOk()

    def __onValueChanged( self, entry):
        self.__value = entry.get_text()
        self.__try2EnableOk()

    def __onCancel( self, button):
        self.__win.destroy()

    def __onOk( self, button):
        self.__var.setName( self.__varname)
        self.__var.setType( self.__type)
        self.__var.setValue( self.__value)
        self.__configWin.addVar( self.__var)
        self.__win.destroy()

